<template>
  <div class="live-page">
    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧区域 -->
      <div class="left-section">
        <!-- 视频播放器区域 -->
        <div class="video-section">
          <div class="video-player">
            <video
              ref="videoRef"
              class="video-element"
              controls
              autoplay
              muted
              playsinline
            ></video>
          </div>
          <!-- 主播信息 -->
          <div class="streamer-info">
            <div class="streamer-header">
              <div class="streamer-avatar">
                <el-avatar :size="48" :src="defaultAvatar" />
              </div>
              <div class="streamer-details">
                <div class="streamer-name">{{ roomInfo.roomName }}</div>
                <div class="live-stats">
                  <span class="viewer-count">
                    <el-icon>
                      <View />
                    </el-icon>
                    {{ roomInfo.roomPersons || 0 }}
                  </span>
                  <span
                    class="live-status"
                    :class="{ active: roomInfo.roomStatus === 1 }"
                  >
                    {{ roomInfo.roomStatus === 1 ? "直播中" : "未开播" }}
                  </span>
                </div>
              </div>
              <div class="action-buttons">
                <el-button type="danger" round>
                  <el-icon>
                    <Star />
                  </el-icon>
                  关注
                </el-button>
                <el-button type="primary" round>
                  <el-icon>
                    <Share />
                  </el-icon>
                  分享
                </el-button>
              </div>
            </div>
            <div class="stream-description">
              <div class="tags">
                <el-tag
                  v-for="tag in roomInfo.roomTags?.split(',')"
                  :key="tag"
                  size="small"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <div class="description-text">{{ roomInfo.roomInformation }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="right-section">
        <div class="chat-container">
          <!-- 聊天消息列表 -->
          <div class="chat-messages" ref="chatMessagesRef">
            <div
              v-for="(message, index) in chatMessages"
              :key="index"
              class="message-item"
            >
              <span class="message-time">{{ message.time }}</span>
              <span class="message-user" :style="{ color: message.userColor }">
                {{ message.userName }}:
              </span>
              <span class="message-content">{{ message.content }}</span>
            </div>
          </div>

          <!-- 聊天输入框 -->
          <div class="chat-input">
            <div class="input-toolbar">
              <el-button-group>
                <el-button size="small">
                  <FontIcon icon-key="SmileFilled" />
                </el-button>
                <el-button size="small">
                  <el-icon>
                    <Picture />
                  </el-icon>
                </el-button>
              </el-button-group>
            </div>
            <div class="input-area">
              <el-input
                v-model="messageInput"
                type="text"
                placeholder="发个友善的弹幕见证当下"
                @keyup.enter="sendMessage"
              >
                <template #append>
                  <el-button type="primary" @click="sendMessage"
                    >发送</el-button
                  >
                </template>
              </el-input>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount,getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { View, Star, Share, Picture } from "@element-plus/icons-vue";
import { getSetting, type LiveSetting } from "@/apis/live";
import { useAppStoreWithOut } from "@/store/modules/app";
import { useWebsoctkeStoreWithOut } from "@/store/modules/websoctke";
import {
  ChatMessageFace,
  ChatType,
  MessageType,
  sendFace,
  serverMessage,
  ServiceMessageContent,
  websoctkeTypes,
} from "@/config/websoctke";
import LinkWebRc from "@/utils/webrc";
import { getMitt } from "@/utils/mitt";
import type {ComponentInternalInstance} from "vue"
const porx = getCurrentInstance()  as ComponentInternalInstance
// import defaultAvatar from '@/assets/default-avatar.png'
const mitt = getMitt();
mitt.on(`${websoctkeTypes.NotificationMessage}`, (e: ServiceMessageContent) => {
  if (e.code !== 1) return;
  console.log("==>", e);
  addMessageData(e);
});
mitt.on(`${websoctkeTypes.SysHi}`, (e: ServiceMessageContent) => {
  if (e.code !== 1) return;
  console.log("==>", e);
  addMessageData(e);
});

const defaultAvatar =
  "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
const route = useRoute();
const videoRef = ref<HTMLVideoElement>();
const chatMessagesRef = ref<HTMLElement>();
const messageInput = ref("");
const store = useAppStoreWithOut();
const storeStore = useWebsoctkeStoreWithOut();
const router = useRouter();
// 房间信息
const roomInfo = ref<LiveSetting>({
  uuid: "",
  roomName: "",
  roomPhoto: "",
  roomInformation: "",
  roomTags: "",
  roomAddress: "",
  roomStatus: 0,
  status: 1,
  roomPersons: 0,
  roomMessagesGroupsId: 0,
  userUuid: "",
});

// 模拟聊天消息
interface ChatMessage {
  userName: string;
  content: string;
  time: string;
  userColor: string;
}

const chatMessages = ref<ChatMessage[]>([]);
const userColors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEEAD"];

// 获取房间信息
const getRoomInfo = async () => {
  const room_uuid = router.currentRoute.value.query.room_uuid as string;
  if (!room_uuid) {
    ElMessage.error("房间ID不能为空");
    return;
  }

  try {
    const res = await getSetting(room_uuid);
    roomInfo.value = res;

    const roomMessagesGroupsId = res.roomMessagesGroupsId;
    const uuid = store.getUserInfo.uuid;
    addRoom({
      uuid,
      groups_id: roomMessagesGroupsId,
      socket_id: storeStore.getSocketId,
    });
    startLive();
  } catch (error) {
    console.error("获取房间信息失败:", error);
    ElMessage.error("获取房间信息失败");
  }
};
const startLive = () => {
  let timer:any = null;
  // let timer = setInterval(() => {
  const ws = `ws://192.168.86.18:3333/app/${roomInfo.value.userUuid}`;
  let linkWebRc = new LinkWebRc(ws, videoRef.value as HTMLVideoElement);
  linkWebRc.onSuccess = () => {
    // isLiving.value = true
    clearInterval(timer);
    porx.ctx.$forceUpdate()
  };

  linkWebRc.onError = () => {
    timer = setTimeout(() => {
      startLive();
    }, 1000);
  };
  linkWebRc.onClose = () => {
    timer = setTimeout(() => {
      startLive();
    }, 1000);
  };
  // }, 1000);
};
const addRoom = (d: any) => {
  const mesg: sendFace = {
    type: websoctkeTypes.AddRoom,
    account_uuid: "",
    data: JSON.stringify(d),
  };
  storeStore.sendMessages(mesg);
  console.log("加入房间");
};
// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim()) return;
  sendChatMessage(messageInput.value);
  messageInput.value = "";

  // 滚动到底部
  setTimeout(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
    }
  }, 0);
};

const sendChatMessage = (text: string) => {
  const data: ChatMessageFace = {
    sender_uuid: store.getUserInfo.uuid,
    content: text,
    group_id: roomInfo.value.roomMessagesGroupsId,
    message_type: MessageType.text,
    chat_type: ChatType.group,
  };
  const s: sendFace = {
    type: websoctkeTypes.SendMessage,
    account_uuid: "",
    data: JSON.stringify(data),
  };
  storeStore.sendMessages(s);
};
const addMessageData = (s: ServiceMessageContent) => {
  const data = s.data as serverMessage;
  const newMessage: ChatMessage = {
    userName: data.nick_name,
    content: s.data.content,
    time: data.create_time,
    userColor: userColors[Math.floor(Math.random() * userColors.length)],
  };

  chatMessages.value.push(newMessage);
  if (chatMessages.value.length > 100) {
    chatMessages.value.shift();
  }

  // 滚动到底部
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
  }
};

onMounted(() => {
  getRoomInfo();
});

onBeforeUnmount(() => {});
const outRoom = () => {
  const roomMessagesGroupsId = roomInfo.value.roomMessagesGroupsId;
  const uuid = store.getUserInfo.uuid;
  const mesg: sendFace = {
    type: websoctkeTypes.LeftRoom,
    account_uuid: "",
    data: JSON.stringify({
      groups_id: roomMessagesGroupsId,
      uuid: uuid,
      socket_id: storeStore.getSocketId,
    }),
  };
  storeStore.sendMessages(mesg);
  console.log("退出房间");
};
const exit = () => {
  mitt.off(`${websoctkeTypes.AddRoom}`);
};
onBeforeUnmount(() => {
  outRoom();
  exit();
});
window.addEventListener("beforeunload", function (event) {
  outRoom();
  exit();
});
</script>

<style scoped lang="scss">
.live-page {
  height: 100%;
  background-color: var(--el-bg-color);

  .main-content {
    display: flex;
    gap: 16px;
    padding: 16px;
    height: 100%;

    .left-section {
      flex: 1;
      min-width: 0;
      display: flex;
      flex-direction: column;
      gap: 16px;

      .video-section {
        background-color: var(--el-bg-color-overlay);
        border-radius: 8px;
        overflow: hidden;

        .video-player {
          width: 100%;
          padding-top: 56.25%; // 16:9 比例
          position: relative;
          background-color: #000;

          .video-element {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }

        .streamer-info {
          padding: 16px;

          .streamer-header {
            display: flex;
            align-items: center;
            gap: 16px;
            margin-bottom: 16px;

            .streamer-details {
              flex: 1;
              min-width: 0;

              .streamer-name {
                font-size: 18px;
                font-weight: 600;
                color: var(--el-text-color-primary);
                margin-bottom: 4px;
              }

              .live-stats {
                display: flex;
                align-items: center;
                gap: 16px;
                color: var(--el-text-color-secondary);
                font-size: 14px;

                .viewer-count {
                  display: flex;
                  align-items: center;
                  gap: 4px;
                }

                .live-status {
                  padding: 2px 8px;
                  border-radius: 12px;
                  background-color: var(--el-color-info-light-9);
                  color: var(--el-color-info);

                  &.active {
                    background-color: var(--el-color-danger-light-9);
                    color: var(--el-color-danger);
                  }
                }
              }
            }

            .action-buttons {
              display: flex;
              gap: 8px;
            }
          }

          .stream-description {
            .tags {
              display: flex;
              flex-wrap: wrap;
              gap: 8px;
              margin-bottom: 8px;
            }

            .description-text {
              color: var(--el-text-color-regular);
              font-size: 14px;
              line-height: 1.5;
            }
          }
        }
      }
    }

    .right-section {
      width: 320px;
      flex-shrink: 0;

      .chat-container {
        height: 100%;
        background-color: var(--el-bg-color-overlay);
        border-radius: 8px;
        display: flex;
        flex-direction: column;

        .chat-messages {
          flex: 1;
          min-height: 0;
          padding: 16px;
          overflow-y: auto;

          .message-item {
            margin-bottom: 8px;
            font-size: 14px;
            line-height: 1.5;

            .message-time {
              color: var(--el-text-color-secondary);
              font-size: 12px;
              margin-right: 8px;
            }

            .message-user {
              font-weight: 500;
              margin-right: 4px;
            }

            .message-content {
              color: var(--el-text-color-primary);
            }
          }
        }

        .chat-input {
          padding: 16px;
          border-top: 1px solid var(--el-border-color-light);

          .input-toolbar {
            margin-bottom: 8px;
          }

          .input-area {
            :deep(.el-input-group__append) {
              padding: 0;

              .el-button {
                margin: 0;
                border: none;
                border-radius: 0 4px 4px 0;
              }
            }
          }
        }
      }
    }
  }
}

// 响应式布��
@media screen and (max-width: 1200px) {
  .live-page {
    .main-content {
      flex-direction: column;

      .right-section {
        width: 100%;
        height: 320px;
      }
    }
  }
}

// 深色模式适配
html.dark {
  .live-page {
    .video-section {
      background-color: var(--el-bg-color-overlay);
    }

    .chat-container {
      background-color: var(--el-bg-color-overlay);
    }
  }
}
</style>
